<template>
  <div class="upload">
    <div class="upload-title">
      <span class="upload-text"><slot name="text"></slot></span>
      <!--<span class="upload-illustrate"><slot name="illustrate">({{$t('message.uploadTip')}})</slot></span>-->
      <span class="upload-illustrate"><slot name="titleTip"></slot></span>
    </div>
    <div class="all-content">
      <div class="upload-left">
	      <div class="upload-btn-group" v-if="isShowBtn === 'none'">
	        <div class="upload-btn" @click="triggerUpload"></div>
	        <input id="picker" type="file" ref="uploadFile" v-show="false" @change="onFileChange"/>
	      </div>
	      <!--loading-->
	      <div class="upload-loading" v-if="isShowBtn === 'loading'">
	      	<div class="loading-img">
	      		{{ $t('message.uploadLoading') }}
	      	</div>
	      </div>
	      <div class="upload-image" v-if="isShowBtn === 'complete'" :style="{ background: 'url(' + this.uploadImage + ') no-repeat center / contain' }" @mouseover="showImageCover" @mouseleave="hideImageCover">
          <!--<img :src="this.uploadImage" alt="">-->
	        <div class="upload-close" @click.prevent="delImage" v-show="isShowImageCover" title="the photo has been deleted"></div>
	      </div>
      </div>
      <div class="upload-right">
        <div class="example-text">
          {{ $t('message.example') }}：
        </div>
        <div class="example-image">
          <slot name="photo">{{ $t('message.studentCard') }}</slot>
        </div>
      </div>
    </div>
    <div class="tip">
    	<span class="upload-illustrate"><slot name="illustrate">({{ $t('message.uploadTip') }})</slot></span>
    </div>
    <div class="error-tips" v-if="checkImgError">
      {{ checkImgErrorTxt }}
    </div>
  </div>
</template>

<script>
export default {
  name: 'VUploadImage',
  props: {
    image: {
      type: String
    },
    deleteImage: {
      type: [Number, String]
    }
  },
  data () {
    return {
      isShowBtn: 'none',
      isShowImageCover: false,
      uploadImage: '',
      checkImgError: false,
      checkImgStatus: 0
    }
  },
  watch: {
    deleteImage () {
      this.delImage()
    }
  },
  computed: {
    checkImgErrorTxt () {
      switch (this.checkImgStatus) {
        case 2:
          return this.$t('message.small2m')
        case 3:
          return this.$t('message.onlyJpg')
      }
    }
  },
  methods: {
    triggerUpload () {
      this.$refs.uploadFile.click()
    },
    onFileChange (e) {
      if (!e.target.files && !e.dataTransfer) {
        this.$store.commit('alert', {
          switch: true,
          alertText: this.$t('message.uploadTip2')
        })
        return
      }
      let fileList = e.target.files || e.DataTransfer.files
      if (fileList.length === 0) {
        return
      } else {
        let files = fileList[0]
        let n = files.type.split('/')
        if (n[1] === 'jpg' || n[1] === 'jpeg' || n[1] === 'png') {
          this.checkImgStatus = 1
          this.checkImgError = false
        } else {
          this.checkImgStatus = 3
          this.checkImgError = true
          return
        }
        this.isShowBtn = 'loading'
/*        this.param = new window.FormData()
        this.param.append('file', files, files.name)
        this.$ajax.uploadImg(this.param).then(res => {
          if (res.code === 200) {
            let img = new Image()
            img.onload = () => {
              this.isShowBtn = 'complete'
              this.uploadImage = res.data.file
              this.isShowImageCover = false
              this.$emit('uploadImage', this.uploadImage)
            }
            img.src = res.data.file
          } else {
            this.$store.commit('alert', {
              switch: true
            })
          }
        }).catch((err) => {
          this.$store.commit('alert', {
            switch: true
          })
        })*/
        let reader = new FileReader()
        reader.readAsDataURL(files)
        let img = new Image()
        let canvas = document.createElement('canvas')
        let context = canvas.getContext('2d')
        let _this = this
        reader.onload = (e) => {
          img.src = e.target.result
        }
        // base64地址图片加载完毕后
        img.onload = function () {
          // 图片原始尺寸
          let originWidth = this.width
          let originHeight = this.height
          // 目标尺寸
          let targetWidth = originWidth
          let targetHeight = originHeight
          // 图片大于2M才压缩
          if (files.size / 1024 > 2048) {
            if (originWidth > 5000 || originHeight > 5000) {  //大于5000
              if (originWidth / originHeight > 1) {
              // 更宽，按照宽度限定尺寸
                targetWidth = 2500
                targetHeight = Math.round(2500 * (originHeight / originWidth))
              } else {
                targetHeight = 2500
                targetWidth = Math.round(2500 * (originWidth / originHeight))
              }
            } else if (originWidth > 4000 || originHeight > 4000) {   //大于4000
              if (originWidth / originHeight > 1) {
                targetWidth = 2000
                targetHeight = Math.round(2000 * (originHeight / originWidth))
              } else {
                targetHeight = 2000
                targetWidth = Math.round(2000 * (originWidth / originHeight))
              }
            } else if (originWidth > 3000 || originHeight > 3000) {  //大于3000
              if (originWidth / originHeight > 1) {
                targetWidth = 1500
                targetHeight = Math.round(1500 * (originHeight / originWidth))
              } else {
                targetHeight = 1500
                targetWidth = Math.round(1500 * (originWidth / originHeight))
              }
            } else if (originWidth > 2000 || originHeight > 2000) {   //大于2000
              if (originWidth / originHeight > 1) {
                targetWidth = 1000
                targetHeight = Math.round(1000 * (originHeight / originWidth))
              } else {
                targetHeight = 1000
                targetWidth = Math.round(1000 * (originWidth / originHeight))
              }
            } else {  // 2000以下
              if (originWidth / originHeight > 1) {
                targetWidth = 800
                targetHeight = Math.round(800 * (originHeight / originWidth))
              } else {
                targetHeight = 800
                targetWidth = Math.round(800 * (originWidth / originHeight))
              }
            }
          }
          // canvas对图片进行缩放
          canvas.width = targetWidth
          canvas.height = targetHeight
          // 清除画布
          context.clearRect(0, 0, targetWidth, targetHeight)
          // 图片压缩
          context.drawImage(img, 0, 0, targetWidth, targetHeight)
          // canvas转为base64并上传
          let switchImg = canvas.toDataURL(files.type)
//          _this.uploadImage = switchImg
//          _this.isShowBtn = 'complete'
//          _this.isShowImageCover = false
          _this.$ajax.updateFile({img: switchImg}).then((res) => {
            if (res.code === 200) {
              let img = new Image()
              img.onload = () => {
                _this.uploadImage = res.data.img
                _this.isShowBtn = 'complete'
                _this.isShowImageCover = false
                _this.$emit('uploadImage', _this.uploadImage)
              }
              img.src = res.data.img
            }
          })
        }
      }
    },
    delImage () {
      this.isShowBtn = 'none'
      this.uploadImage = undefined
      this.$emit('uploadImage', '')
    },
    showImageCover () {
      this.isShowImageCover = true
    },
    hideImageCover () {
      this.isShowImageCover = false
    }
  },
  created () {
    if (!this.image) return
    this.uploadImage = this.image
    this.isShowBtn = 'complete'
  }
}
</script>

<style scoped>
.upload-title {
	height: 22px;
	font-size: 0;
	padding-left: 18px;
	position: relative;
}

.upload-title:before {
	content: '';
	display: block;
	width: 4px;
	height: 15px;
	background-color: #ff600a;
	position: absolute;
	top: 3px;
	left: 0;
}

.upload-text {
	line-height: 22px;
  font-size: 16px;
  font-weight: bold;
  color: #333333;
  margin-right: 16px;
}

.all-content {
	height: 200px;
  margin-top: 40px;
}

.all-content:after {
	content: '';
	width: 0;
	height: 0;
	display: block;
	clear: both;
	visibility: hidden;
}

.upload-left {
  width: 400px;
  height: 200px;
  border-right: 1px solid #E5E5E5;
  box-sizing: border-box;
  float: left;
}

.upload-btn-group {
  width: 200px;
  height: 200px;
}

.upload-btn {
  width: 200px;
  height: 200px;
  border: 1px dashed #d7d7d7;
  background: #fafafa;
  box-sizing: border-box;
  position: relative;
  cursor: pointer;
}

.upload-btn:before, .upload-btn:after {
	content: '';
	display: block;
	background-color: #e7e7e7;
	border-radius: 2px;
	position: absolute;
	top: 50%;
	left: 50%;
}

.upload-btn:before {
	width: 4px;
	height: 48px;
	margin-left: -2px;
	margin-top: -24px;
}

.upload-btn:after {
	width: 48px;
	height: 4px;
	margin-left: -24px;
	margin-top: -2px;
}

.upload-loading {
  width: 200px;
  height: 200px;
  border: 1px dashed #d7d7d7;
  background: #fafafa url(../../assets/images/upload_loading.gif) no-repeat center 80px;
  box-sizing: border-box;
}

.loading-img {
  line-height: 17px;
  margin: 120px auto 0;
  font-size: 12px;
  color: #a5a5a5;
  text-align: center;
}

.upload-image {
  width: 200px;
  height: 200px;
  position: relative;
  border: 1px dashed #D7D7D7;
  box-sizing: border-box;
}

.upload-close {
	width: 24px;
	height: 24px;
	background: url(../../assets/images/register/icon_delPhoto.png) no-repeat center;
	position: absolute;
	top: -13px;
	right: -13px;
	cursor: pointer;
}

.upload-right {
	float: left;
  padding-left: 60px;
}

.example-text {
  font-size: 14px;
  color: #333;
  font-weight: bold;
  margin-bottom: 16px;
}

.example-image {
  width: 200px;
  height: 140px;
}

.example-image img {
  width: 100%;
  height: 100%;
}

.tip {
  margin-top: 12px;
  line-height: 20px;
}

.upload-illustrate {
  font-size: 14px;
  color: #A5A5A5;
}
</style>
